﻿using SuperSocket;
using SuperSocket.ProtoBase;
using SuperSocket.Command;
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace GpsServer
{
    [Command(Key = ProtocolNo.STATUS)]
    public class StatusCommand : IAsyncCommand<MyPackageInfo>
    {
        private readonly ILogger _logger;

        public StatusCommand(ILogger<StatusCommand> logger)
        {
            _logger = logger;
        }

        public async ValueTask ExecuteAsync(IAppSession session, MyPackageInfo package)
        {
            var mySession = (MySession)session;
            if (!mySession.IsLogin || package.Content.Length < 5) return;

            //终端信息
            var str = Convert.ToString(package.Content[0], 2).PadLeft(8, '0');
            var defense = str[0] == '1';//设防/撤防
            var acc = str[1] == '1';//ACC开关
            var outPower = str[2] == '1';//是否接通外电源
            AlarmType alarm;//报警类型
            switch (str.Substring(3, 3))
            {
                case "000":
                    alarm = AlarmType.None;
                    break;
                case "001":
                    alarm = AlarmType.Shake;
                    break;
                case "010":
                    alarm = AlarmType.Outage;
                    break;
                case "011":
                    alarm = AlarmType.LowBattery;
                    break;
                case "100":
                    alarm = AlarmType.SOS;
                    break;
                default:
                    alarm = AlarmType.None;
                    return;
            }
            var gps = str[6] == '1';//GPS是否定位
            var powerOff = str[7] == '1';//油电是否断开
            //电压等级
            var voltageLevel = (int)package.Content[1];
            //GSM信号
            var gsmLevel = (int)package.Content[2];
            //扩展位

            _logger.LogDebug("STATUS: Terminal={0} Defense={1} ACC={2} OutPowder={3} Alarm={4} GPS={5} PowerOff={6} VoltageLevel={7} GSMLevel={8}"
                , mySession.TerminalID, defense, acc, outPower, alarm, gps, powerOff, voltageLevel, gsmLevel);

            //响应
            var data = Helper.StringToHexByte("787805010001D9DC0D0A");
            await session.SendAsync(data);
        }
    }
}